﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Bk.Model;
using Bk.Models;

namespace WebApplication1.Controllers
{
    public class HomeController : Controller
    {
       
        public ActionResult Person()
        {
            ViewBag.ActiveMenu = "Person";
            int userId = Convert.ToInt32(Session["UserInfo"]);
            using (var db = new bloggerEntitiesW())
            {
                var user = db.UserInfo.FirstOrDefault(u => u.UserId == userId);
                var self = db.SelfInfo.FirstOrDefault(s => s.UserId == userId);
                var model = new PersonViewModel
                {
                    NickName = self?.Nike ?? "",
                    Gender = self?.Sex ?? "",
                    Introduction = self?.Blurb ?? "",
                    Description = self?.Describe ?? ""
                };
                ViewBag.ImageUrl = user?.Image ?? "";
                return View(model);
            }
        }
        //上传头像
        public ActionResult Uploadface()
        {
            ViewBag.ActiveMenu = "Uploadface";
            int userId = Convert.ToInt32(Session["UserInfo"]);
            using (var db = new bloggerEntitiesW())
            {
                var user = db.UserInfo.FirstOrDefault(u => u.UserId == userId);
                ViewBag.ImageUrl = user?.Image ?? "";
            }
            return View();
        }

        [HttpPost]
        public ActionResult Uploadface(HttpPostedFileBase file)
        {
            if (Session["UserInfo"] == null)
                return Json(new { success = false, message = "请先登录" });
            int userId = Convert.ToInt32(Session["UserInfo"]);
            if (file != null && file.ContentLength > 0)
            {
                string fileName = Guid.NewGuid().ToString() + System.IO.Path.GetExtension(file.FileName);
                string path = Server.MapPath("~/Uploads/Avatars/");
                if (!System.IO.Directory.Exists(path))
                    System.IO.Directory.CreateDirectory(path);
                string filePath = System.IO.Path.Combine(path, fileName);
                file.SaveAs(filePath);
                using (var db = new bloggerEntitiesW())
                {
                    var user = db.UserInfo.FirstOrDefault(u => u.UserId == userId);
                    if (user != null)
                    {
                        user.Image = "/Uploads/Avatars/" + fileName;
                        db.SaveChanges();
                    }
                }
                return Json(new { success = true, imageUrl = "/Uploads/Avatars/" + fileName });
            }
            return Json(new { success = false, message = "请选择图片" });
        }
        //我的博客
        public ActionResult Blog()
        {
            ViewBag.ActiveMenu = "Blog";
            int userId = Convert.ToInt32(Session["UserInfo"]);
            using (var db = new bloggerEntitiesW())
            {
                var categoryDict = new Dictionary<string, string>
                {
                    { "1", "艺术" },
                    { "2", "文学" },
                    { "3", "体育" },
                    { "4", "生活" }
                };
                var blogs = db.BlogInfo
                    .Where(b => b.UserId == userId)
                    .OrderByDescending(b => b.BId)
                    .ToList();
                foreach (var blog in blogs)
                {
                    if (!string.IsNullOrEmpty(blog.categories+"") && categoryDict.ContainsKey(blog.categories + ""))
                        blog.categoriesName = categoryDict[blog.categories + ""];
                    blog.PushDateStr = blog.PushDate.HasValue ? blog.PushDate.Value.ToString("yyyy-MM-dd") : "";
                }
                return View(blogs);
            }
        }
        //创作、写文章
        public ActionResult Create()
        {
            return View();
        }

        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Create(string title, string substance, int categories, string tags, string summary, HttpPostedFileBase coverImage)
        {
            try
            {
                // 检查用户是否登录
                if (Session["UserInfo"] == null)
                {
                    TempData["ErrorMessage"] = "请先登录后再发表文章";
                    return RedirectToAction("Login", "Default");
                }

                int userId = Convert.ToInt32(Session["UserInfo"]);

                // 验证必填字段
                if (string.IsNullOrWhiteSpace(title))
                {
                    ModelState.AddModelError("title", "请输入文章标题");
                }
                else if (title.Length < 5)
                {
                    ModelState.AddModelError("title", "文章标题至少需要5个字符");
                }

                if (string.IsNullOrWhiteSpace(substance))
                {
                    ModelState.AddModelError("substance", "请输入文章内容");
                }

                if (categories <= 0)
                {
                    ModelState.AddModelError("categories", "请选择文章分类");
                }

                if (!ModelState.IsValid)
                {
                    return View();
                }

                using (var db = new bloggerEntitiesW())
                {
                    // 创建新的博客文章
                    var blogPost = new BlogInfo
                    {
                        title = title,
                        Substance = substance,
                        categories = categories,
                        UserId = userId,
                        Likes = 0,
                        PushDate = DateTime.Now,
                        PushDateStr = DateTime.Now.ToString("yyyy-MM-dd")
                    };

                    // 处理封面图片上传
                    if (coverImage != null && coverImage.ContentLength > 0)
                    {
                        string fileName = Guid.NewGuid().ToString() + System.IO.Path.GetExtension(coverImage.FileName);
                        string path = Server.MapPath("~/Uploads/Covers/");
                        if (!System.IO.Directory.Exists(path))
                            System.IO.Directory.CreateDirectory(path);
                        string filePath = System.IO.Path.Combine(path, fileName);
                        coverImage.SaveAs(filePath);
                        // 这里可以将封面路径保存到数据库的某个字段中
                        // blogPost.CoverImage = "/Uploads/Covers/" + fileName;
                    }

                    db.BlogInfo.Add(blogPost);
                    
                    if (db.SaveChanges() > 0)
                    {
                        TempData["SuccessMessage"] = "文章发表成功！";
                        return RedirectToAction("Blog", "Home");
                    }
                    else
                    {
                        ModelState.AddModelError("", "文章发表失败，请重试");
                    }
                }
            }
            catch (Exception ex)
            {
                ModelState.AddModelError("", "发表文章时发生错误：" + ex.Message);
            }

            return View();
        }
        //修改资料
        public ActionResult ModifyData()
        {
            ViewBag.ActiveMenu = "ModifyData";
            if (Session["UserInfo"] == null)
            {
                return RedirectToAction("Login", "Default");
            }
            int userId = Convert.ToInt32(Session["UserInfo"]);
            using (var db = new bloggerEntitiesW())
            {
                var user = db.UserInfo.FirstOrDefault(u => u.UserId == userId);
                var self = db.SelfInfo.FirstOrDefault(s => s.UserId == userId);
                var model = new PersonViewModel
                {
                    NickName = self?.Nike ?? string.Empty,
                    Gender = self?.Sex ?? string.Empty,
                    Introduction = self?.Blurb ?? string.Empty,
                    Description = self?.Describe ?? string.Empty
                };
                ViewBag.ImageUrl = user?.Image ?? "";
                return View(model);
            }
        }

        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult ModifyData(PersonViewModel model)
        {
            ViewBag.ActiveMenu = "ModifyData";
            if (Session["UserInfo"] == null)
            {
                return RedirectToAction("Login", "Default");
            }
            if (!ModelState.IsValid)
            {
                return View(model);
            }

            int userId = Convert.ToInt32(Session["UserInfo"]);
            using (var db = new bloggerEntitiesW())
            {
                var user = db.UserInfo.FirstOrDefault(u => u.UserId == userId);
                var self = db.SelfInfo.FirstOrDefault(s => s.UserId == userId);

                //if (user != null)
                //{
                //    user.UserName = model.NickName ?? string.Empty;
                //}

                if (self == null)
                {
                    self = new SelfInfo
                    {
                        UserId = userId,
                        Nike = model.NickName ?? string.Empty,
                        Image = string.Empty,
                        SelfIntroduction = string.Empty
                    };
                    db.SelfInfo.Add(self);
                }

                // 同步个人信息
                self.Nike = model.NickName ?? string.Empty;
                self.Sex = model.Gender ?? string.Empty;
                self.Blurb = model.Introduction ?? string.Empty;
                self.Describe = model.Description ?? string.Empty;

                db.SaveChanges();
            }

            TempData["SuccessMessage"] = "资料已更新";
            return RedirectToAction("ModifyData");
        }
        //修改密码
        public ActionResult ChangePassword()
        {
            ViewBag.ActiveMenu = "ChangePassword";
            return View();
        }

        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult ChangePassword(string oldPassword, string newPassword, string confirmPassword)
        {
            ViewBag.ActiveMenu = "ChangePassword";
            if (Session["UserInfo"] == null)
            {
                return RedirectToAction("Login", "Default");
            }
            if (string.IsNullOrWhiteSpace(newPassword) || newPassword.Length < 6)
            {
                TempData["ErrorMessage"] = "密码长度不能少于6位";
                return RedirectToAction("ChangePassword");
            }
            if (newPassword != confirmPassword)
            {
                TempData["ErrorMessage"] = "新密码和确认密码不一致";
                return RedirectToAction("ChangePassword");
            }

            int userId = Convert.ToInt32(Session["UserInfo"]);
            using (var db = new bloggerEntitiesW())
            {
                var user = db.UserInfo.FirstOrDefault(u => u.UserId == userId);
                if (user == null)
                {
                    TempData["ErrorMessage"] = "用户不存在";
                    return RedirectToAction("ChangePassword");
                }
                if ((user.PassWord ?? string.Empty) != (oldPassword ?? string.Empty))
                {
                    TempData["ErrorMessage"] = "原密码不正确";
                    return RedirectToAction("ChangePassword");
                }

                user.PassWord = newPassword;
                user.ConfirmPassword = newPassword;
                db.SaveChanges();
            }

            TempData["SuccessMessage"] = "密码修改成功";
            return RedirectToAction("ChangePassword");
        }
    }
}